import java.io.BufferedWriter;
import java.io.File;
import java.nio.*;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.LinkOption;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchEvent.Modifier;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URI;
import java.util.Iterator;
import java.util.Properties;

import javax.swing.JOptionPane;

public class SmartKiwiSender {
	

	public static void main(String args[])
	{

		Socket socket = null;
		PrintWriter pred= null;
		try {
			String str = System.getenv("SMART_KIWI_WINDOWS");
			String[] aPath = str.split(";");
			File f = null;
			boolean exists=false;
			for(String path : aPath)
			{
				f = new File(path+"\\config.properties");
				if(f.exists())
				{
					exists = true;	
					break;
				}
			}
			if(exists)
			{
				Properties props = new Properties();
				FileInputStream inp = new FileInputStream(f);
				props.load(inp);
				int port = Integer.parseInt(props.getProperty("port"));
					socket = new Socket("localhost", port);
			        pred = new PrintWriter(
			                             new BufferedWriter(
			                                new OutputStreamWriter(socket.getOutputStream())), 
			                             true);
			        if(args.length > 0)
			        {
				        String filePath = args[0];
				        String forceFiche="";
				        if(args.length > 1)
				        	forceFiche = args[1];
						pred.write("SENDDOCUMENT \"" + filePath + "\" " +forceFiche);
			        }
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NumberFormatException e){
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		if(pred != null)
			pred.close();
		if(socket != null)
		{
			try {
				socket.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
